package com.rising.face.ali.bishi.consumer;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author LiChenYang
 * @description 利用阻塞队列模拟生产者消费者
 * @date 2022-12-14 16:52
 */
public class ConAndProducerQueue {

    /**
     * 库存
     */
    private LinkedBlockingQueue<Integer> stock;

    public ConAndProducerQueue(int sum) {
        this.stock = new LinkedBlockingQueue(sum);
    }

    public void producer() {
        while (true) {
            try {
                stock.put(1);
                System.out.println("线程：" + Thread.currentThread().getName() + ", 生产一个，剩余：" + stock.size());
                int sleep = new Random().nextInt(1000) + 300;
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void consumer() {
        while (true) {
            try {
                if (stock.take() != null) {
                    System.out.println("线程：" + Thread.currentThread().getName() + ", 消费一个，剩余：" + stock.size());
                    int sleep = new Random().nextInt(1000) + 500;
                    Thread.sleep(sleep);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        ConAndProducerQueue queue = new ConAndProducerQueue(10);
        new Thread(new Runnable() {
            @Override
            public void run() {
                queue.producer();
            }
        }, "AA").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                queue.producer();
            }
        }, "AA2").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                queue.consumer();
            }
        }, "BB").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                queue.consumer();
            }
        }, "BB2").start();
    }
}
